package com.lgx.mobile.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.lgx.common.basic.dao.GeneralDao;
import com.lgx.common.exception.DataException;
import com.lgx.mobile.dao.IFriendDao;
import com.lgx.mobile.entity.Friend;

/**
 * 
 * @author xuyichen
 *
 */
@Component("friendDao")
public class FriendDao extends GeneralDao implements IFriendDao {

	protected Logger log = Logger.getLogger(this.getClass());
	
	public Friend createFriend(Friend friend) throws DataException {
		this.getHibernateTemplate().save(friend);
		log.info("[创建好友]:"+friend.getId());
		return friend;
	}

	public Friend updateFriend(Friend friend) throws DataException {
		this.getHibernateTemplate().update(friend);
		log.info("[更新好友]:"+friend.getId());
		return friend;
	}

	public void deleteFriend(Friend friend) throws DataException {
		log.info("[删除好友]:"+friend.getId());
		this.getHibernateTemplate().delete(friend);
	}

	public void deleteFriendById(long id) throws DataException {
		log.info("[删除好友]:"+id);
		this.deleteFriend(this.findFriendById(id));
	}

	public Friend findFriendById(long id) {
		return this.getHibernateTemplate().get(Friend.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public Friend checkFriendExists(long onwerUserId,long friendUserId){
		String sql = "from Friend f where f.onwerUserId = "+onwerUserId+" and f.friendUserId = "+friendUserId;
		List<Friend> list = this.getHibernateTemplate().find(sql);
		if(list.size() == 0){
			return null;
		}
		return list.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public List<Friend> findFriendListByOnwerUserId(long onwerUserId){
		String sql = "from Friend f where f.onwerUserId = "+onwerUserId+" order by f.id asc";
		return this.getHibernateTemplate().find(sql);
	}
	
	@SuppressWarnings("unchecked")
	public List<Friend> findFriendList(){
		String sql = "from Friend f order by f.id asc";
		return this.getHibernateTemplate().find(sql);
	}
}
